package com.shushan.pages;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.bean.MaketingActivityBean;
import com.shushan.pages.bean.MaketingDataBean;
import com.shushan.pages.bean.WXPayBean;
import com.shushan.service.DialRTAService;
import com.shushan.service.WechatShareRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.shushanbao.wxapi.WXEntryActivity;
import com.shushan.shushanbao.wxapi.WXPayEntryActivity;
import com.shushan.util.ImageUtils;
import com.shushan.util.PayUtils;
import com.shushan.util.PopupWindowUtil;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.shushan.util.WxApiUtils;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * @ClassName: InviteForFreeUseActivity
 * @Desciption: //分享营销--邀请页
 * @author: zhangshihao
 * @date: 2018-05-22
 */
public class InviteForFreeUseActivity extends NavigationLoseActivity implements View.OnClickListener {

    private static final String TAG = InviteForFreeUseActivity.class.getSimpleName();

    private Button btnBuy7DayVip;
    private RelativeLayout rlInviteNow;
    private PopupWindow sharePopupWindow;

    private MaketingDataBean maketingDataBean;

    private Bitmap shareBmp;

    private IWXAPI api;
    private BabyApplication babyApplication = BabyApplication.getInstance();
    private boolean hideTaste;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_for_free_use);
        setTitle("邀请好友助学");

        hideTaste = getIntent().getBooleanExtra("hideTaste",false);

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.registerApp(Constants.APP_ID);

        initView();

        getMaketingData();

        getData();

        UmengEventUtil.onEvent(babyApplication,"invite_friends_page_id");
    }

    @Override
    protected void onResume() {
        super.onResume();
        setAllowBack(false);
    }

    private void initView() {
        rlInviteNow = findViewById(R.id.rl_invite_now);
        rlInviteNow.setOnClickListener(this);
        btnBuy7DayVip = findViewById(R.id.btn_buy_7day_vip);
        btnBuy7DayVip.setOnClickListener(this);
        if(babyApplication.isPayVip() || hideTaste){
            btnBuy7DayVip.setVisibility(View.GONE);
        }else {
            btnBuy7DayVip.setVisibility(View.VISIBLE);
        }

    }

    private void getData() {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.IMG_SHARE);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {

                    @Override
                    protected void onCommon() {
                        //do nothing
                    }

                    @Override
                    protected void onSuccess(String data) {
                        Log.i(TAG, "data : " + data);
                        try {
                            JSONObject jobj = new JSONObject(data);
                            final String url = jobj.optString("url", "");
                            shareBmp = ImageUtils.getNetwrokBitmap(url);
                        } catch (JSONException je) {
                            je.printStackTrace();
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        Log.d(TAG, netRetBean.toString());
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        boolean result;
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);

        switch (v.getId()) {
            case R.id.rl_invite_now:
                WXEntryActivity.type = 1;
                sharePopupWindow = PopupWindowUtil.showShareWechatPopupWindow(this,this,getWindow().getDecorView());
                break;
            case R.id.iv_wechat_share_friend://分享到对话
                sharePopupWindow.dismiss();
                if (shareBmp == null) {
                    showToast("未获取到分享图片，正在重新获取，请稍候再试");
                    getData();
                    return;
                }

                if(isChildControl){
                    setAllowBack(true);
                    Intent intent = new Intent(this,WechatShareRTAService.class);
                    intent.putExtra("allowPackName",Constants.ALLOW_WECHAT_PACK_NAME);
                    startService(intent);
                }

                result = WxApiUtils.sharePic(InviteForFreeUseActivity.this, WxApiUtils.SHARE_TYPE_SESSION, shareBmp);
                Log.i(TAG, "图片分享--对话 ： " + result);

                UmengEventUtil.onEvent(babyApplication,"invite_friends_click_id","weixin");
                break;
            case R.id.iv_wechat_share_friends_circle://分享到朋友圈
                sharePopupWindow.dismiss();
                if (shareBmp == null) {
                    showToast("未获取到分享图片，正在重新获取，请稍候再试");
                    getData();
                    return;
                }

                if(isChildControl){
                    setAllowBack(true);
                    Intent intent = new Intent(this,WechatShareRTAService.class);
                    intent.putExtra("allowPackName",Constants.ALLOW_WECHAT_PACK_NAME);
                    startService(intent);
                }

                result = WxApiUtils.sharePic(InviteForFreeUseActivity.this, WxApiUtils.SHARE_TYPE_TIME_LINE, shareBmp);
                Log.i(TAG, "图片分享--朋友圈 ： " + result);

                UmengEventUtil.onEvent(babyApplication,"invite_friends_click_id","circle");
                break;
            case R.id.tv_cancel://取消
                sharePopupWindow.dismiss();
                break;
            case R.id.btn_buy_7day_vip://购买7天vip
                setAllowBack(true);

                if("oppo".equals(BuildConfig.ENVIRONMENT)){
                    if(maketingDataBean == null){
                        showToast("分享营销数据为空");
                        return;
                    }

                    List<MaketingActivityBean> maketingBeanList = maketingDataBean.getMaketingActivityBeanList();
                    if(ToolUtils.isListEmpty(maketingBeanList)){
                        showToast("活动信息为空");
                        return;
                    }
                    if(maketingBeanList.size() < 2){
                        showToast("10元购买7天VIP活动未开始");
                        return;
                    }

                    MaketingActivityBean maketingActivityBean = maketingBeanList.get(1);
                    PayUtils.orderOppoSupperPay(this,maketingActivityBean.id,maketingActivityBean.vip_time,maketingActivityBean.favorable_price);
                }else if(getPackageName().equals(Constants.MASTER_PACKAGE_NAME)){
                    orderPay();
                }else {
                    PayUtils.openVipHuawei(this,maketingDataBean);
                }

                UmengEventUtil.onEvent(babyApplication,"experience_buy_click_id");
                break;
            default:
                break;
        }
    }

    private void orderPay() {
        if(api.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            showToast("您未安装最新版本微信，不支持微信支付，请安装或升级微信版本");
            return;
        }

        if(maketingDataBean == null){
            showToast("分享营销数据为空");
            return;
        }

        List<MaketingActivityBean> maketingBeanList = maketingDataBean.getMaketingActivityBeanList();
        if(ToolUtils.isListEmpty(maketingBeanList)){
            showToast("活动信息为空");
            return;
        }
        if(maketingBeanList.size() < 2){
            showToast("10元购买7天VIP活动未开始");
            return;
        }
        MaketingActivityBean maketingActivityBean = maketingBeanList.get(1);
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.PAY_ORDER);
        urlParse.putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("goods_name",maketingActivityBean.favorable_price + "元购买" + maketingActivityBean.vip_time + "天VIP活动")
                .putValue("vip_time",maketingActivityBean.vip_time)
                .putValue("activity_vip_id",maketingActivityBean.id);

        if(BuildConfig.DEBUG){
            urlParse.putValue("money","0.01");
        }else {
            urlParse.putValue("money",maketingActivityBean.favorable_price);
        }

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<WXPayBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(WXPayBean wxPayBean) {
                        if(wxPayBean != null){
                            PayReq req = new PayReq();
                            req.appId			= wxPayBean.appid;
                            req.partnerId		= wxPayBean.partnerid;
                            req.prepayId		= wxPayBean.prepayid;
                            req.nonceStr		= wxPayBean.noncestr;
                            req.timeStamp		= wxPayBean.timestamp + "";
                            req.packageValue	= wxPayBean.packageName;
                            req.sign			= wxPayBean.sign;
                            req.extData			= "app data"; // optional

                            Log.i(TAG,"out_trade_no=" + wxPayBean.out_trade_no);
                            SharedPreferencesUtils.setStringDate(Constants.OUT_TRADE_NO_SHAREPREFERS_KEY,wxPayBean.out_trade_no);
                            WXPayEntryActivity.type = 5;

                            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
                            if(isChildControl){
                                setAllowBack(true);
                                Intent intent = new Intent(InviteForFreeUseActivity.this,DialRTAService.class);
                                intent.putExtra("rtaType",4);
                                intent.putExtra("allowPackName",Constants.ALLOW_WECHAT_PACK_NAME);
                                startService(intent);
                            }

                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
                        }else {
                            showToast("返回数据为空");
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void getMaketingData(){
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.MEMBER_CENTER);
        UrlParse paramParse = new UrlCommParse(this).putValue("phone",SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<MaketingDataBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(MaketingDataBean maketDataBean) {
                        maketingDataBean = maketDataBean;
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

}
